package org.example.dao.impl;

import org.example.dao.ProductDao;
import org.example.entity.Product;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductDaoImpl implements ProductDao {
    @Override
    public void addProduct(Product product) {
        String sql = "INSERT INTO db_product VALUES (NULL,?,?,?);";
        int row = DBUtil.executeSql(sql,product.getProName(),product.getStock(),product.getPrice());
        if(row > 0){
            System.out.println("添加成功");
        }
    }

    @Override
    public void delProductImpl(String name) {
        String sql = "DELETE FROM db_product WHERE pro_name = ?";
        int row = DBUtil.executeSql(sql,name);
        if(row > 0){
            System.out.println("删除成功");
        }
    }

    @Override
    public void updProductImpl(int number, String name) {
        String sql = "UPDATE db_product SET stock = ? WHERE pro_name = ?";
        int row = DBUtil.executeSql(sql,number,name);
        if(row > 0){
            System.out.println("更新成功");
        }
    }

    public Product getProduct(String name) {
        String sql = "SELECT * FROM db_product WHERE pro_name = ?;";
        List<Product> list = new ArrayList<>();
        list = DBUtil.executeQuery(Product::map,sql,name);
        if(list.size() > 0){
            return list.get(0);
        }
        return null;
    }

    @Override
    public double getPriceByProName(String proName) {
        String sql = "SELECT price FROM db_product WHERE pro_name = ?";
        try (Connection conn = DBUtil.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, proName);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getDouble("price");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
